import { createRouter, createWebHashHistory } from "vue-router";
import type { App } from "vue";
// @ts-ignore
import routes from "virtual:generated-pages";
import nprogress from "nprogress";
import { useUserStore } from "@/store/modules/user";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: "/admin/main"
    },
    {
      path: "/admin",
      redirect: "/admin/main"
    },
    ...routes
  ]
});
router.beforeEach(async (to, _from, next) => {
  nprogress.start();
  const userStore = useUserStore();
  if (!userStore.getToken) {
    if (to.name != "login") {
      next("/login");
      nprogress.done();
    } else {
      next();
    }
  } else {
    next();
  }
});
router.afterEach((to, from) => {
  // 路由跳转完毕后关闭进度条
  nprogress.done();
  to.meta.transition =
    (to.meta.pageIndex || 0) > (from.meta.pageIndex || 0) ? "slide-left" : "slide-right";
});
// 路由准备就绪后挂载APP实例
export async function setupRouter(app: App) {
  app.use(router);
  // 路由准备就绪后挂载APP实例
  await router.isReady();
}

export default router;
